package handlers

import (
	"errors"
	"gitee.com/aqchain/backend/models"
	"gitee.com/aqchain/go-ethereum/common"
	jwt "github.com/appleboy/gin-jwt/v2"
	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
	"strconv"
)

// Register 注册
func (h *Handler) Register(c *gin.Context) {
	err := h.register(c)
	if err != nil {
		c.JSON(200, gin.H{
			"success": false,
			"message": err.Error(),
		})
		return
	}

	c.JSON(200, gin.H{
		"success":          true,
		"currentAuthority": "user",
	})
}

func (h *Handler) register(c *gin.Context) error {
	mail := c.PostForm("mail")
	username := c.PostForm("username")
	password := c.PostForm("password")

	var user models.User
	h.db.First(&user, models.User{Mail: mail})
	if &user != nil && user.ID > 0 {
		return errors.New("email existed")
	}
	user = models.User{Username: username, Mail: mail}
	user.Password, _ = cryptoPassword([]byte(password))
	user.RoleID = 1

	err := h.db.Create(&user).Error
	if err != nil {
		return err
	}

	return nil
}

func (h *Handler) CurrentUser(c *gin.Context) {
	claims := jwt.ExtractClaims(c)
	userID := claims["userID"]
	var user models.User
	h.db.First(&user, userID)
	c.JSON(200, user)
}

func (h *Handler) GetUser(c *gin.Context) {
	// 获取参数并检查
	userID, err := strconv.ParseUint(c.Query("userID"), 10, 64)
	if err != nil {
		c.JSON(200, gin.H{
			"success": false,
			"message": "error params",
		})
		return
	}

	var user models.User
	err = h.db.First(&user, userID).Error
	if err != nil || user.ID == 0 {
		c.JSON(200, gin.H{
			"success": false,
			"message": "user not found",
		})
		return
	}

	c.JSON(200, gin.H{
		"success": true,
		"data":    user,
	})

}

// AddAccount 添加绑定区块链账户
func (h *Handler) AddAccount(c *gin.Context) {

	err := h.addAccount(c)
	if err != nil {
		c.JSON(200, gin.H{
			"success": false,
			"message": err.Error(),
		})
		return
	}

	c.JSON(200, gin.H{
		"success": true,
	})
}

func (h *Handler) addAccount(c *gin.Context) error {
	// 获取参数并检查
	userID, err := strconv.ParseUint(c.PostForm("userID"), 10, 64)

	if err != nil {
		return errParams
	}

	// 检查区块链账户地址格式
	address := c.PostForm("address")
	if !common.IsHexAddress(address) {
		return errAddress
	}

	// 查找用户
	var user models.User
	err = h.db.First(&user, userID).Error
	if err != nil || user.ID == 0 {
		return errUserNotFound
	}

	err = h.db.Where(&user).Updates(models.User{Address: address}).Error
	if err != nil {
		return err
	}

	return nil
}

func cryptoPassword(password []byte) (string, error) {
	cipher, err := bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost)
	if err != nil {
		return "", err
	}
	return string(cipher), nil
}
